import request from '../utils/request.js'

const HOMEWORK_API_BASE = 'http://localhost:9100' // homework-service 端口

export const homeworkAPI = {
  // 获取所有作业列表
  getHomeworkList: (params = {}) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework/list`,
      method: 'get',
      params
    })
  },

  // 根据ID获取作业详情
  getHomeworkById: (id) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework/${id}`,
      method: 'get'
    })
  },

  // 根据班级ID获取作业列表
  getHomeworkByClassId: (classId, params = {}) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework/class/${classId}`,
      method: 'get',
      params: {
        page: 0,
        size: 50,
        sortBy: 'createTime',
        sortDir: 'desc',
        ...params
      }
    })
  },

  // 创建新作业
  createHomework: (data) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework`,
      method: 'post',
      data
    })
  },

  // 更新作业
  updateHomework: (id, data) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework/${id}`,
      method: 'put',
      data
    })
  },

  // 删除作业
  deleteHomework: (id) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework/${id}`,
      method: 'delete'
    })
  },

  // 获取作业提交记录
  getHomeworkSubmissions: (homeworkId) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/teacher/homework/${homeworkId}/submissions`,
      method: 'get'
    })
  },

  // 获取学生提交的作业文件
  getSubmissionFiles: (submitId) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/teacher/homework/submission/${submitId}/files`,
      method: 'get'
    })
  },

  // 获取文件下载链接
  getFileDownloadUrl: (fileId) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/teacher/homework/file/${fileId}/download`,
      method: 'get'
    })
  },

  // 批量获取文件下载链接
  getBatchFileDownloadUrls: (fileIds) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/teacher/homework/files/batch-download`,
      method: 'post',
      data: fileIds
    })
  },

  // 提交作业 (学生端功能)
  submitHomework: (homeworkId, data) => {
    const formData = new FormData()
    formData.append('homeworkId', homeworkId)
    formData.append('userId', data.userId)
    if (data.content) {
      formData.append('content', data.content)
    }
    if (data.files && data.files.length > 0) {
      data.files.forEach(file => {
        formData.append('files', file)
      })
    }
    
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework-submit`,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 检查学生是否已提交作业
  checkStudentSubmitted: (homeworkId, userId) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework-submit/homework/${homeworkId}/user/${userId}/check`,
      method: 'get'
    })
  },

  // 获取学生的作业提交记录
  getStudentSubmission: (homeworkId, userId) => {
    return request({
      url: `${HOMEWORK_API_BASE}/api/homework-submit/homework/${homeworkId}/user/${userId}`,
      method: 'get'
    })
  },

  // 上传作业文件
  uploadHomeworkFile: (file, uploaderId) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('uploaderId', uploaderId)
    
    return request({
      url: `${HOMEWORK_API_BASE}/api/files/upload`,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// 文件下载工具
export const downloadUtils = {
  // 通过URL下载文件
  downloadByUrl: (url, fileName = 'download') => {
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileName)
    link.setAttribute('target', '_blank')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },

  // 批量下载文件
  batchDownload: async (fileIds) => {
    try {
      const response = await homeworkAPI.getBatchFileDownloadUrls(fileIds)
      if (response.code === 200 && response.data && response.data.length > 0) {
        response.data.forEach((url, index) => {
          setTimeout(() => {
            window.open(url, '_blank')
          }, index * 500) // 延迟500ms避免浏览器阻止多个下载
        })
      } else {
        throw new Error(response.message || '未能获取批量下载链接')
      }
    } catch (error) {
      console.error('批量下载失败:', error)
      throw error
    }
  }
}

export default homeworkAPI
